'''
Created on 2013-1-11

@author: hanchen
'''
# encoding: utf-8

from zheezes.po.ip_addr import IpAddr 
from zheezes.util.ip_addr import ip_str_to_int
from zheezes.util.ip_addr import ip_int_to_str
from zheezes.util.ip2addr import qq_ip_to_addr

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

def get_next_ip():
    rs = IpAddr.gql("ORDER BY ip DESC LIMIT 1");
    ipaddr = rs.get()
    return ip_int_to_str(ip_str_to_int(ipaddr.ip) + 1)

def imp_ip_addr(ip):
    rs = IpAddr.gql("WHERE ip = :ip LIMIT 1", ip=ip);
    ipaddr = rs.get()
    if not ipaddr:
        ipaddr = IpAddr()
        ipaddr.ip = ip
    addr = qq_ip_to_addr(ip)
    # addr = "ok"
    ipaddr.addr = addr
    ipaddr.put()
    
class MainPage(webapp.RequestHandler):
    def get(self):
        bip = self.request.get("bip")
        count = self.request.get("count")
        if not bip:
            bip = get_next_ip()
        if count:
            count = int(count)
        else:
            count = 1
        bip = ip_str_to_int(bip)
        # bip = ip_str_to_int("111.222.84.123")
        cnt = 0
        for ip in range(bip, bip + count):
            try:
                imp_ip_addr(ip_int_to_str(ip))
                cnt = cnt + 1
            except:
                break
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write("%s, %s, %s" % (ip_int_to_str(bip), count, cnt))

application = webapp.WSGIApplication([('/.*', MainPage)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
